home *** CD-ROM | disk | FTP | other *** search
Java Source | 1997-04-20 | 2.7 KB | 99 lines |
- import java.io.*;
- import java.net.*;
- import java.awt.*;
-
- /**
- * NumberClient -- The client program for the guessing game.
- *
- * To run as a client, name the server as the first command line
- * argument:
- * java NumberClient bluehorse.com
- * or
- * java NumberClient local // to run locally
- */
-
- public class NumberClient {
- private int port = 5001; // The default port.
- private Socket sock;
- private DataInputStream remoteIn;
- private DataOutputStream remoteOut;
- private boolean listening = true;
-
- public static void main(String args[]) {
-
- if (args.length != 1) {
- System.out.println("format is: java NumberClient <hostname>");
- return;
- }
-
- new NumberClient().client(args[0]);
- }
-
- // As a client, we create a socket bound to the specified port,
- // connect to the specified host, and then start communicating
- // over the network via the socket.
-
- private void client(String serverName) {
- DataInputStream in = new DataInputStream(System.in);
-
- try {
- if (serverName.equals("local"))
- serverName = null;
-
- InetAddress serverAddr = InetAddress.getByName(serverName);
- sock = new Socket(serverAddr.getHostName(), port, true);
- remoteIn = new DataInputStream(sock.getInputStream());
- remoteOut = new DataOutputStream(sock.getOutputStream());
-
- while (listening) {
- String s = in.readLine();
- if (s.equals(""))
- listening = false;
- else
- remoteOut.writeUTF(s);
-
- String response = remoteIn.readUTF();
- System.out.println(response);
- }
-
- } catch (IOException e) {
- System.out.println(e.getMessage() +
- ": Connection with server closed.");
-
- } finally {
- try {
- if (remoteIn != null) {
- remoteIn.close();
- remoteIn = null;
- }
-
- if (remoteOut != null) {
- remoteOut.close();
- remoteOut = null;
- }
-
- if (sock != null) {
- sock.close();
- sock = null;
- }
-
- } catch (IOException x) {
- }
- }
- }
-
- protected void finalize() throws Throwable {
- try {
- if (remoteIn != null)
- remoteIn.close();
- if (remoteOut != null)
- remoteOut.close();
- if (sock != null)
- sock.close();
- } catch (IOException x) {
- }
- super.finalize();
- }
-
- }
-